//
// Created on 2024/4/29.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "FlowItemNode.h"

#include <memory>
#include "NativeNodeApi.h"

FlowItemNode::FlowItemNode()
    : ArkUINode(NativeNodeApi::getInstance()->createNode(ArkUI_NodeType::ARKUI_NODE_FLOW_ITEM)),
      m_flowItemNodeDelegate(nullptr) {
    maybeThrow(NativeNodeApi::getInstance()->registerNodeEvent(m_nodeHandle, NODE_ON_CLICK, 0, this));
}

void FlowItemNode::insertChild(ArkUINode &child, std::size_t index) {
    maybeThrow(NativeNodeApi::getInstance()->insertChildAt(m_nodeHandle, child.getArkUINodeHandle(),
                                                           static_cast<int32_t>(index)));
}

void FlowItemNode::removeChild(ArkUINode &child) {
    maybeThrow(NativeNodeApi::getInstance()->removeChild(m_nodeHandle, child.getArkUINodeHandle()));
}

void FlowItemNode::setFlowItemNodeDelegate(FlowItemNodeDelegate *flowItemNodeDelegate) {
    m_flowItemNodeDelegate = flowItemNodeDelegate;
}

void FlowItemNode::onNodeEvent(ArkUI_NodeEventType eventType, EventArgs &eventArgs) {
    if (eventType == ArkUI_NodeEventType::NODE_ON_CLICK && eventArgs[3].i32 != 2) {
        onClick();
    }
}

void FlowItemNode::onClick() {
    if (m_flowItemNodeDelegate != nullptr) {
        m_flowItemNodeDelegate->onClick();
    }
}

FlowItemNode &FlowItemNode::setMargin(float left, float top, float right, float bottom) {
    ArkUI_NumberValue value[] = {{.f32 = top}, {.f32 = right}, {.f32 = bottom}, {.f32 = left}};
    ArkUI_AttributeItem item = {value, sizeof(value) / sizeof(ArkUI_NumberValue)};
    maybeThrow(NativeNodeApi::getInstance()->setAttribute(m_nodeHandle, NODE_MARGIN, &item));
    return *this;
}

FlowItemNode::~FlowItemNode() { NativeNodeApi::getInstance()->unregisterNodeEvent(m_nodeHandle, NODE_ON_CLICK); }

FlowItemNode &FlowItemNode::setAlign(int32_t align) {
    ArkUI_NumberValue value[] = {{.i32 = align}};
    ArkUI_AttributeItem item = {.value = value, .size = 1};
    maybeThrow(NativeNodeApi::getInstance()->setAttribute(m_nodeHandle, NODE_STACK_ALIGN_CONTENT, &item));
    return *this;
}
